package data.platform.timescale.internal.monitor;

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.lang.NonNull;
import io.r2dbc.pool.ConnectionPool;

public class PoolingMetricsBinder implements MeterBinder {

    private final ConnectionPool connectionPool;

    public PoolingMetricsBinder(ConnectionPool connectionPool) {
        this.connectionPool = connectionPool;
    }


    @Override
    public void bindTo(@NonNull MeterRegistry registry) {
        registerTotalMetrics(registry);
    }

    private void registerTotalMetrics(MeterRegistry registry) {
        Gauge.builder("r2dbc.pool.acquiredSize",
                connectionPool,
                (connectionPool) -> connectionPool.getMetrics().get().acquiredSize())
                .register(registry);

        Gauge.builder("r2dbc.pool.allocatedSize",
                connectionPool,
                (connectionPool) -> connectionPool.getMetrics().get().allocatedSize())
                .register(registry);


        Gauge.builder("r2dbc.pool.pendingAcquireSize",
                connectionPool,
                (connectionPool) -> connectionPool.getMetrics().get().pendingAcquireSize())
                .register(registry);
    }

}
